package ua.com.stormlabs.tiny.licenseserver.controllers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ua.com.stormlabs.tiny.licenseserver.beans.User;
import ua.com.stormlabs.tiny.licenseserver.service.UsersService;
import ua.com.stormlabs.tiny.licenseserver.storage.UserNotFoundException;

/**
 * @author Denis Bondarenko
 * @version 1.0 Nov 16, 2010
 */
@Controller
public class ServiceController {

    private final static Logger log = LoggerFactory.getLogger(ServiceController.class);

    @Autowired
    private UserRequestsValidator userRequestsValidator;

    @Autowired
    UsersService usersService;

    @RequestMapping(value = "service/validate", method = RequestMethod.GET)
    public ResponseEntity validate(@RequestParam String userName, @RequestParam String key, @RequestParam String opaque,
                                   @RequestParam String mac) {
        log.info("Validating license: user=[" + userName + "], key=[" + key + "], opaque=[" + opaque + "], mac=["
                + mac + "]");
        String response = userRequestsValidator.buildResponse(userName, key, mac, opaque);
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<String>(response, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "service/getUserInfo", method = RequestMethod.GET,
            produces = "application/xml")
    @ResponseBody
    public User getUserInfo(@RequestParam String userName, @RequestParam String key, @RequestParam String opaque,
                            @RequestParam String mac) {
        log.info("Validating license: user=[" + userName + "], key=[" + key + "], opaque=[" + opaque + "], mac=["
                + mac + "]");
        if (userRequestsValidator.isValidUser(userName, key, opaque, mac)) {
            try {
                return usersService.getUserByName(userName);
            } catch (UserNotFoundException e) {
                log.info("No user with name: " + userName);
                return null;
            }
        } else {
            return null;
        }
    }
}
